package com.g17.virtualpetbackend.controller;

import com.g17.virtualpetbackend.entity.Paper;
import com.g17.virtualpetbackend.entity.Test;
import com.g17.virtualpetbackend.entity.User;
import com.g17.virtualpetbackend.service.PaperService;
import com.g17.virtualpetbackend.service.TestService;
import com.g17.virtualpetbackend.service.UserService;
import com.g17.virtualpetbackend.utilty.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class TestController {

    private static Logger logger = LoggerFactory.getLogger(TestController.class);

    @Autowired
    private TestService testService;

    @Autowired
    private PaperService paperService;

    @Autowired
    private UserService userService;


    @GetMapping("/test")
    public List<Test> getAllTests() {
        return testService.getAllTests();
    }

    @RequestMapping(value = "/test/{id}", method = RequestMethod.GET)
    public Test getTest(@PathVariable("id") Long id) {
        return testService.getTestById(id);
    }

    @PostMapping("/test")
    public Response insertQuestion(@RequestBody Map<String, String> params) {
        Test test;
        if (params.get("id") != null) {
            logger.info(params.get("id"));
            test = testService.updateTest(params);
        } else {
            logger.info("create");
            test = testService.createTest(params);
        }
        if (test == null) {
            return new Response(Response.ERROR_ID, Response.ERROR);
        } else {
            return new Response(test.getId(), Response.OK);
        }
    }

    @DeleteMapping("/test")
    public Response deleteQuestion(@RequestParam("id") String id) {
        Long deleteTestId = testService.deleteTest(Long.parseLong(id));
        if (deleteTestId != -1) {
            return new Response(deleteTestId, Response.OK);
        } else {
            return new Response(deleteTestId, Response.ERROR);
        }
    }

    @PostMapping("/paper")
    public Response generatePaper(@RequestBody Map<String, String> params) {
        String questionIds = params.get("id");
        Paper paper = paperService.createPaper(questionIds);
        if (paper.getId() == null) {
            return new Response((long) -1, Response.ERROR);
        } else {
            return new Response(paper.getId(), Response.OK);
        }
    }

    @GetMapping("/paper")
    public List<Paper> getAllPapers() {
        return paperService.getAllPapers();
    }

    @PostMapping("/testStudent")
    public Map<String, Object> addStudentToPaper(@RequestBody Map<String, String> params) {
        Map<String, Object> result = new HashMap<>();
        Long paperId = Long.valueOf(params.get("paperid"));
        String[] usernames = params.get("username").split(",");
        String time = params.get("time");
        Paper paper = paperService.distributePaperToStudent(paperId, usernames, time);
        logger.info(paper.toString());
        List<User> attendUsers = paperService.getAttendedUserByPaper(paper.getId());
        List<User> addUsers = userService.findAllUserByUsernames(usernames);
        if (attendUsers.containsAll(addUsers)) {
            result.put("status_code", Response.OK);
            result.put("paperid", paperId);
            result.put("username", usernames);
        } else {
            result.put("status_code", Response.ERROR);
        }
        return result;
    }

    @GetMapping("/testStudent")
    public Map<String, Object> getAttendedStudent(@RequestParam("paperid") String paperId) {
        Map<String, Object> result = new HashMap<>();
        List<User> userList = paperService.getAttendedUserByPaper(Long.valueOf(paperId));
        StringBuilder usernameList = new StringBuilder();
        if (userList.size() > 0) {
            for (User user : userList) {
                usernameList.append(user.getUsername());
                usernameList.append(",");
            }
            usernameList = new StringBuilder(usernameList.substring(0, usernameList.length() - 1));
        }
        result.put("username", usernameList.toString());
        return result;
    }

    @GetMapping("/takeTest")
    public Map<String, Object> takeTest(@Param("username") String username, @Param("paperid") String paperid) {
        Map<String, Object> result = new HashMap<>();
        if (username != null) {
            List<Paper> userPapers = paperService.getAttendPaperByUser(username);
            result.put("paper", userPapers);
        } else if (paperid != null){
            List<Test> testList = testService.getTestByPaperId(Long.valueOf(paperid));
            result.put("tests", testList);
        }
        return result;
    }

    @DeleteMapping("/testStudent")
    public Map<String, Object> deleteAttendedUser(@RequestParam("paperid") String paperId, @RequestParam("username") String username) {
        Map<String, Object> result = new HashMap<>();
        if (paperService.deleteUserToPaper(Long.valueOf(paperId), username) != -1) {
            result.put("success_code", Response.OK);
        } else {
            result.put("success_code", Response.ERROR);
        }
        return result;
    }

    @PostMapping("/handIn")
    public Map<String, Object> handInPaper(@RequestBody Map<String, String> params) {
        Map<String, Object> result = new HashMap<>();
        Long paperId = Long.valueOf(params.get("paperid"));
        String[] questionId = params.get("id").split(",");
        String[] questionChosen = params.get("question").split(",");
        String username = params.get("username");
        Float score = testService.calculateScore(questionId, questionChosen);
        if (score.equals(paperService.insertScore(paperId, username, score))) {
            result.put("score", score);
        } else {
            result.put("score", Response.ERROR_ID);
        }
        return result;
    }

}
